package com.wd.tw.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * @className: HttpUtils
 * @description: TODO 类描述
 * @author: liumingkun
 * @date: 2024/11/3
 **/
public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);


    public static String post(String urlString, String param) {

        logger.info("request url:" + urlString);
        String result = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
//            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            connection.setDoOutput(true);
            connection.setDoInput(true);
            OutputStreamWriter out = null;
            BufferedReader in = null;
            // 发送请求

            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            out.write(param);
            out.flush();

            // 读取返回数据
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = "";
            boolean firstLine = true; // 读第一行不加换行符
            while ((line = in.readLine()) != null) {
                if (firstLine) {
                    firstLine = false;
                }
                result += line;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
